package top.lingkang.securityoauth2.client.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.lingkang.securityoauth2.client.config.Oauth2ClientProperties;
import top.lingkang.securityoauth2.client.constants.FinalConstants;
import top.lingkang.securityoauth2.client.error.FinalPermissionException;
import top.lingkang.securityoauth2.core.entity.UserDetail;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * @author lingkang
 * Created by 2022/7/1
 * HttpServletRequest上下文的使用
 */
public abstract class FinalSecurityContext {
    private static Oauth2ClientProperties securityProperties;
    private static String[] serverURL = new String[]{};

    public static void init(Oauth2ClientProperties securityProperties) {
        FinalSecurityContext.securityProperties = securityProperties;
        serverURL = FinalSecurityContext.securityProperties.getServerURL();

    }

    private static final ThreadLocal<UserDetail> userDetail = new ThreadLocal<>();

    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static UserDetail getUserDetail() {
        UserDetail user = userDetail.get();
        if (user != null)
            return user;
        String token = getToken();
        HashMap<String, String> head = new HashMap<>();
        head.put("Authorization", "Bearer " + token);
        String result = securityProperties.getHttpRequest().get(
                serverURL + "/oauth2/info",
                head
        );
        user = JSON.toJavaObject(JSONObject.parseObject(result), UserDetail.class);
        System.out.println(user);
        userDetail.set(user);
        return user;
    }

    public static String getToken() {
        String token = securityProperties.getGetToken().getToken(getRequest());
        if (token == null) {
            throw new FinalPermissionException(FinalConstants.UNAUTHORIZED_MSG);
        }
        return token;
    }

    public static void setUserDetail(UserDetail detail) {
        userDetail.set(detail);
    }
}
